/**
 * 
 */
package com.dems.core.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.net.ssl.SSLContext;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * @author dxpeng
 *
 */
public class HttpClientUtils {

	private static final String YIBEI_API_NAME = "dqbg";
	private static final String YIBEI_APP_KEY = "ba6f7a7f53d2c2a54c80699400dcb722";
	private static final String YIBEI_API_SECRET = "b623690414594b330bc1d7e998ac977e51aea98f080feb8c5939fd59ce856a0d";
	private static final String YIBEI_API_VERSION = "1.1.0";

	static Logger logger = LogManager.getLogger(HttpClientUtils.class);
	
	private static CloseableHttpClient buildSSLCloseableHttpClient() throws Exception {
	     SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
		 //信任所有
		 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		     return true;
		 }
	    }).build();
	    //ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作，并且不会抛出javax.net.ssl.SSLException异常。
	    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null,  
	            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	}


	public static String sendHttpRequestPost(String url,String transferData ) throws Exception{
		
		String resultJson="";

		HttpClient httpclient =  buildSSLCloseableHttpClient();

		
		try{

			//String transferData=urlencode(params);
			
			HttpPost httpPost=new HttpPost(url);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
			
			StringEntity se = new StringEntity(new String(transferData.getBytes("UTF-8"),"ISO-8859-1"));
			
			se.setContentType("application/x-www-form-urlencoded");
			//se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
			httpPost.setEntity(se);
			; 
			HttpResponse response=httpclient.execute(httpPost);
			
			if(response.getStatusLine().getStatusCode()==200){ 
				InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), "UTF-8");
				
				char[] buff = new char[1024];
				int length = 0;

				while ((length = reader.read(buff)) != -1) {
					String temp = new String(buff, 0, length);
					resultJson+=temp;
				}
				//resultJson = EntityUtils.toString(response.getEntity()); 
			}
			
		}catch(Exception e){
			logger.error("#############Http通讯异常#########"+e.getMessage(),e);
			e.printStackTrace();
			
		}finally{
			httpclient.getConnectionManager().shutdown();
		}
		
		
		return resultJson;
		
	}

	
	public static String getData(String api,String userName,String cardNo,String orderNo){
		//StringBuffer sb = new StringBuffer();
		
		JSONObject paramsJson=new JSONObject();
		paramsJson.put("appkey", YIBEI_APP_KEY);
		paramsJson.put("version", YIBEI_API_VERSION);
		paramsJson.put("api", api);
		paramsJson.put("username", userName);
		paramsJson.put("idcard", cardNo);
		paramsJson.put("uid", orderNo);
		paramsJson.put("mobile", "13999999999");
		paramsJson.put("link_name", "");
		paramsJson.put("link_mobile", "");
		paramsJson.put("ts", System.currentTimeMillis() /1000);
		paramsJson.put("sign", sign(paramsJson));
		
		return urlencode(paramsJson);
	}

	//签名
	public static String sign(JSONObject data){
		StringBuffer sb = new StringBuffer();
		
		Map<String, String> map = new TreeMap<String, String>();

		map.put("mobile", "13999999999");
		map.put("link_name", "");
		map.put("link_mobile", "");
		map.put("appkey", YIBEI_APP_KEY);
		map.put("version", YIBEI_API_VERSION);
		map.put("api", data.getString("api"));
		map.put("username", data.getString("username"));
		map.put("idcard", data.getString("idcard"));
		map.put("uid", data.getString("uid"));
		map.put("ts", data.getString("ts"));
		map.put("appsecret", YIBEI_API_SECRET);

		TreeMap<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>(){

		    @Override
		    public int compare(String str1, String str2) {

		        return str1.compareTo(str2);
		    }});

		sortMap.putAll(map);

		try{ 
			Iterator<Entry<String, String>> it = sortMap.entrySet().iterator();
			while(it.hasNext()){//排序得到的字符串
				Entry<String, String> entry = it.next();
		        sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			

			
		}catch(Exception e){
			logger.error("#############签名失败#########"+e.getMessage(),e);
			e.printStackTrace();
		}
		
		return SHA1Utils.SHA1Encode(sb.toString().substring(0, sb.length()-1));
		
	}
	
	//转码
	public static String urlencode(Map<String,Object>data){
		StringBuffer sb = new StringBuffer();
		try{

			for(Entry i: data.entrySet()){
				sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
			}
		}catch(Exception e){
			logger.error("#############转码失败#########"+e.getMessage(),e);
			e.printStackTrace();
		}
		return sb.toString().substring(0, sb.length()-1);
	}


	public static void main(String[] args) {
		String username="陈虎侠";
		String cardNo="622425199005207631";
		String api="dqbg";
		String orderNo="20190803150100001";
		String transferString=getData(api, username, cardNo, orderNo);//请求参数
		String url="https://api.yibeixinxi.com/dqbg";
		try {
			String result=sendHttpRequestPost(url,transferString);
			logger.info(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
